<template>
  <div class="event-detail-edit-view" :class="rootElementClassNames" v-loading.fullscreen.lock="loading">
    <!-- 操作按钮 -->
    <div v-if="!agendaEvent" class="fe-page-header">
      <div class="fe-page-header__left">
        {{ pageTitle }}
      </div>
      <div class="fe-page-header__right">
        <FormCellChange class="mar-r-8" :count="formCellCount" @update="(e)=>{formCellCount=e}"></FormCellChange>
        <el-button type="plain-third" @click="handleBack">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleSave">{{$t('common.base.save')}}</el-button>
      </div>
    </div>

    <!-- 事件基本信息 -->
    <div class="event-form-container">
    <div class="event-basic-info">
      <!-- <div class="info-title">事件基本信息</div> -->
      <event-edit-form :class="agendaEvent ? 'agenda-event-form' : ''" v-if="isInit" :agenda-event="agendaEvent" 
                       :init-data="initData" :fields.sync="basicFields" :types="eventTypeList" 
                       :plan-start-time="startTime" :plan-end-time="endTime" 
                       :url-params="urlParams" :value.sync="basicValue" 
                       :plan-time-config="planTimeConfig"
                       :is-copy="isCopy"
                       ref="formEditRef" @updatetemplateId="updateEventTemplateId"
                       :form-cell-count="formCellCount"
                       @updateSynergyByCustomer="updateSynergyByCustomer"
                        :formEditingMode="formEditingMode"
                       @getDeleteFiles="getDeleteFiles">
      </event-edit-form>
    </div>
    
    <!-- 事件分配信息 -->
    <div v-if="showEventAllotInformation" class="mt_12 event-assign-info bbx-cell-form-builder">
      <div class="info-title">{{$t('event.edit.text1')}}</div>
      
      <el-form class="info-content" label-position="top" :model="eventAssignForm" :rules="assignRules" ref="eventAssignForm" :class="[agendaEvent ? 'agenda-event-info-content' : '', `bbx-cell-form-box-${formCellCount}`, formCellCount > 1 ? 'info-content-forCell bbx-normal-form-builder-cell' : '']">
        <el-form-item class="bbx-form-cell-item form-item" :label="$t('event.edit.text4')" v-if="!agendaEvent && isAuto">
          <el-radio-group v-model="eventAssignIsAuto" @change="eventAssignRadioChange">
            <el-radio :label="false" >{{$t('event.edit.text2')}}</el-radio>
            <el-radio :label="true">{{$t('common.event.actionStatus.autoDispatch')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="bbx-form-cell-item form-item" v-if="!eventAssignIsAuto" :label="$t('common.fields.executorUser.displayName')" prop="executorName">
          <p @click="checkDept(0)" class="p-input">
            <template v-if="isOpenData">
              <open-data type='userName' :openid="executor.staffId"></open-data>
            </template>
            <template v-else>
              {{executorName}}
            </template>
            <el-button type="primary" @click="executorMySelf">{{$t('event.edit.text3')}}</el-button>
          </p>
        </el-form-item>
        <el-form-item class="bbx-form-cell-item form-item" :label="$t('common.fields.synergies.displayName')" prop="synergiesNames">
          <p @click="checkDept(1)" class="p-input">
            <template v-if="isOpenData && synergies && synergies.length">
              <open-data v-for="item in synergies" :key="item.staffId" type='userName' :openid="item.staffId"></open-data>
            </template>
            <template v-else>
              {{synergiesNames}}
            </template>
          </p>
        </el-form-item>
      </el-form>
    </div>
    </div>
    <!--start 事件需要审批弹窗 -->
    <event-need-approve-dialog ref="eventNeedApproveDialog" :title="$t('event.edit.text5')" :remark-required="approveRemark" :event-id="workEventId" @closed="createEventWithoutApprove" :event-no="workEvent.eventNo||eventNo"></event-need-approve-dialog>
    <!--end 事件需要审批弹窗 -->

    <!--  高级审批  -->
    <AdvancedApprovalDialog
      :bizNo="workEvent.eventNo || eventNo"
      :objId="workEventId"
      :remark-required="approveRemark"
      ref="AdvancedApprovalDialogRef"
      @closed="createEventWithoutApprove"
      @success="createEventWithoutApprove"
    />
    <!-- 审批弹窗 -->
  </div>
</template>

<script>
import http from '@src/util/http';
import AuthUtil from '@src/util/auth';
import { isOpenData, openAccurateTab, backToFromAccurateTab } from '@src/util/platform'
import _ from 'lodash';
import EditMixins from './EditMixins'
import * as EventApi from '@src/api/EventApi.js';
import * as TaskApi from '@src/api/TaskApi.ts';
import { getCustomerExeinsyn } from '@src/api/CustomerApi'
import { parse } from '@src/util/querystring';
import * as FormUtil from '@src/component/form/util'
import * as util from '@src/modules/event/util/event'
import { scrollIntoFirstRequireDom } from '@src/util/dom';
/* components*/
import EventEditForm from '@src/modules/event/components/EventEditForm/EventEditForm.vue'
import { initVersionLimitDialog } from '@src/component/business/BizVersionLimitDialog/index.tsx'
import EventNeedApproveDialog from '../eventDetailView/components/Dialog/EventNeedApproveDialog'
import AdvancedApprovalDialog from 'src/component/compomentV2/AdvancedApproval/AdvancedApprovalDialog.vue'

import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum'
import { bindCustomer } from '@src/api/ProductV2Api'
import { isFunction } from '@src/util/type'
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import { safeNewDate } from '@src/util/time';
import { RESOURCE_PREFIX } from '@src/util/linkSwitch'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { chooseExUser } from '@model/config/SelectUserConfig.ts'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormViewTime, disposeFormSubmitTime } = useFormTimezone()
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* mixins */
import { ConnectorModuleConnectorCreateEventMixin } from '@src/modules/connector'
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue'

export default {
  name: 'event-edit-view',
  mixins: [EditMixins, VersionMixin, ConnectorModuleConnectorCreateEventMixin],
  provide() {
    return {
      // 事件是否编辑
      isEdit: this.isEdit
    }
  },
  props: {
    agendaEvent: {
      type: Boolean,
      default: false
    },
    planStartTime: {
      type: String,
      default: ''
    },
    planEndTime: {
      type: String,
      default: ''
    },
    eventTypeListInit: {
      type: Array,
      default: () => []
    },
    planTimeConfig: {
      type: Number,
      default: 30
    }
  },
  data() {
    return{
      pageTitle: '',
      isOpenData,
      initData: {},
      workEvent: {},
      loading: false,
      eventBasicForm: {},
      eventAssignForm: {},
      dialogForm: {},
      defaultTypeId: '',
      eventId: '',
      basicValue: {},
      basicFields: [],
      isInit: false,
      synergies: [],
      synergiesNames: '',
      executor: {},
      executorId: '',
      executorName: '',
      taskTemplate: {},
      eventAssignIsAuto: false, // 单选项是否自动分配
      dialogRules: {
        approveId: [
          { required: true, message: this.$t('event.edit.text6'), trigger: 'blur' },
        ]
      },
      dialogVisible: false,
      selfCanChooseApprove: false,
      approvePending: false,
      approver: {}, // 审批人
      approversName: '',
      approversStaffIds: [],
      saveFormUrl: '',
      createFromCustomerId: '',
      createFromProductId: '',
      initParams: {},
      isCopy: false,
      workEventId:' ',
      eventNo:'',
      eventTypeObj: {},
      formCellCount: 1,
      needServerDeleFiles:[],
      formEditingMode:'',
      externalContactInfo: {},
      isExternalContact: false
    }
  },
  watch: {
    approver(value) {
      const { userId, displayName } = value;
      this.dialogForm.approveId = userId
      this.approversName = displayName
    }
  },
  computed: {
    /** 事件分配信息规则*/
    assignRules() {
      return this.isEventExecutorUser ? ({}) : ({
        executorName: [
          { required: true, message: this.$t('event.edit.text7'), trigger: 'blur' },
        ],
      });
    },
    // 是否开启客户解绑
    productCreateUnBindCustomer(){
      return this.initData?.productCreateUnBindCustomer
    },
    event() {
      return this.initData?.event || {}
    },
    auth() {
      return this.initData?.auth || {}
    },
    isEdit() {
      return this.workEvent.id && !this.fromCopy && !this.fromCus && !this.fromPro
    },
    /** 
     * @description 分配事件权限
    */
    isCaseAllot() {
      return AuthUtil.hasAuth(this.auth, 'CASE_ALLOT');
    },
    /** 
     * @description 显示事件分配信息
     * 1.产品要求没有事件分配权限就不显示事件分配信息
     * 2.(!this.isEdit || this.fromCopy) 这俩之前就有 我复制的
    */
    showEventAllotInformation() {
      return this.isCaseAllot && (!this.isEdit || this.fromCopy);
    },
    urlParams() {
      return parse(window.location.search);
    },
    approveRemark() {
      return this.initData.serviceStationConfig ? this.initData.serviceStationConfig.approveRemark : false
    },
    // approveRemark() {
    //   return this.initData.ssConfig ? this.initData.ssConfig.approveRemark : false
    // },
    // 允许新建事件时不指派负责人
    isEventExecutorUser() {
      return this.initData.serviceStationConfig ? this.initData.serviceStationConfig.eventExecutorUser : false
    },
    isAuto() {
      return this.initData.serviceStationConfig ? this.initData.serviceStationConfig.autoDispatchEnabled : false
    },
    myID() {
      return this.initData.currentUser ? this.initData.currentUser.userId : ''
    },
    myplayName() {
      return this.initData.currentUser ? this.initData.currentUser.displayName : ''
    },
    callRecordId() {
      return this.initData.callRecordId || ''
    },
    templateId() {
      return this.initData.defaultType ? this.initData.defaultType.id : ''
    },
    templateName() {
      return this.initData.defaultType ? this.initData.defaultType.name : ''
    },
    typeListJson() {
      return this.initData.typeListJson || []
    },
    copyTypeListJson() {
      return this.initData.eventTypeList || []
    },
    eventTypeList() {
      if(this.eventTypeObj?.writeList) {
        return this.eventTypeObj.writeList || []
      }
      // 如果是从日程过来的话就取日程中initData中的数据
      if(this.agendaEvent) {
        return this.eventTypeListInit
      }
      return this.typeListJson.length > 0 ? this.typeListJson : this.copyTypeListJson
    },
    fromCus() {
      return this.initData.fromCus || false
    },
    fromPro() {
      return this.initData.fromPro || false
    },
    fromCopy() {
      return this.initData.fromCopy || false
    },


    linkman() {
      return this.initData?.linkman || {}
    },
    address() {
      return this.initData?.address || {}
    },
    startTime() {
      let planStartTime = this.initData?.workEvent?.planStartTime
      return this.planStartTime
    },
    endTime() {
      const planEndTime = this.initData?.workEvent?.planEndTime
      return this.planEndTime
    }
  },
  created () {
    this.$eventBus.$on('agenda-event-executor', this.setExecutor)
    this.$eventBus.$on('agenda-event-synergy', this.setSynergy)
  },
  async mounted() {
    // if(this.agendaEvent) {
    //   // 事件日程默认协同人有自己
    //   this.synergies = [this.loginUser]
    //   this.synergiesNames = this.loginUser.displayName
    // }
    this.loading = true
    await this.queryInitData()
    await this.fetchTypeList()
    await this.initialize()
    await this.getEventTemplateFields()
    
    try {
      // 连接器处理
      this.fetchConnectorInsertSelectCall()
    } catch (error) {
      console.warn(error)
    }
    
    this.loading = false
    this.isInit = true
    
    this.$nextTick(() => {
      this.$refs?.eventAssignForm?.clearValidate()

      // 外部联系人
      if(!this.urlParams?.linkmanId && this.urlParams?.from === 'callcenter') {
        const { linkmanName, linkmanPhone, customerName } = this.urlParams || {};

        // 绑定客户
        this.$refs.formEditRef.updateCustomerValue([{
          label: customerName,
          value: null,
          id: null
        }])
        // 绑定联系人
        this.$refs.formEditRef.bindLinkman({
          id: null,
          name: linkmanName,
          phone: linkmanPhone
        })
      }
    })

    if(this.isEdit){
      this.formEditingMode = 'edit'
    }else{
      this.formEditingMode = 'create'
    }
    
  },
  destroyed () {
    this.removeConnectorCreateSessionData()
    this.$eventBus.$off('agenda-event-executor', this.setExecutor)
    this.$eventBus.$off('agenda-event-synergy', this.setSynergy)
  },
  methods: {
    async fetchTypeList() {
      try {
        const { succ = true, status, data  } = await EventApi.getServiceEventTypeList()
        if(succ) {
          this.eventTypeObj = data
        }
      } catch(e) {
          console.error('【fetch EventApi.fetchTypeList error】', e)
      }
    },
    setExecutor(user){
      this.executor = user ? user : {};
      this.executorId = user ? user.userId : '';
      this.executorName = user ? user.displayName : '';
      this.$set(this.eventAssignForm, 'executorName', user ? user.displayName : '')
    },
    setSynergy(user){
      if(Array.isArray(user)) {
        this.synergies = user
        this.synergiesNames = this.synergies.map(item => item.displayName).join(',')
      } else {
        const index = this.synergies.findIndex(item=>item.userId == user.userId)
        if(index == -1) {
          this.synergies.push(user)
          this.synergiesNames = this.synergies.map(item => item.displayName).join(',')
        }
      }
    },
    // 从何处 新建/编辑 & 获取初始化数据
    async queryInitData() {
      const query = parse(window.location.search)
      let pathName = window.location.pathname
      if(pathName.indexOf(RESOURCE_PREFIX) > -1) pathName = pathName.replace(RESOURCE_PREFIX, '')
      
      let fetchInitDataApi = EventApi.queryEventEditInitData
      let initParams = {
        // eventId: '', // 编辑or复制事件
        // defaultTypeId: '',
        // id: '', // 如果是从客户or产品创建
        // newTemplateId: '', // 复制事件
      }

      document.title = this.$t('common.pageTitle.pageCreateEvent');

      if(this.agendaEvent) {
        // 新建事件日历
        const { id } = this.eventTypeListInit[0]
        this.defaultTypeId = id
        initParams.defaultTypeId = id
      }
      if(query.defaultTypeId) {
        // 新建
        this.defaultTypeId = query.defaultTypeId
        initParams.defaultTypeId = query.defaultTypeId
      }
      if (pathName.indexOf('/event/edit') >= 0 && pathName !== '/event/edit4CallCenter') {
        // 编辑
        initParams.eventId = pathName.split('/event/edit/')[1] || ''
        if(initParams.eventId) document.title = this.$t('common.pageTitle.pageEditEvent');
      } else if (pathName.indexOf('/event/copyEvent') >= 0) {
        // 从复制事件
        fetchInitDataApi = EventApi.queryEventEditInitData4Copy
        initParams.newTemplateId = query.newTemplateId
        initParams.eventId = query.id
        this.defaultTypeId = query.newTemplateId
        this.isCopy = true
      } else if (pathName.indexOf('/event/createFromCustomer') >= 0) {
        // 从客户
        fetchInitDataApi = EventApi.queryEventEditInitData4Customer
        initParams.id = pathName.split('/event/createFromCustomer/')[1]
      } else if (pathName.indexOf('/event/createFromProduct') >= 0) {
        // 从产品
        fetchInitDataApi = EventApi.queryEventEditInitData4Product
        initParams.id = pathName.split('/event/createFromProduct/')[1]
      } else if ( pathName.indexOf('/event/edit4CallCenter') >= 0 ) {
        // 从呼叫中心
        fetchInitDataApi = EventApi.queryEventEdit4CallCenterInit
        initParams = { ...query }
      }
      this.pageTitle = document.title

      this.initParams = initParams
      await fetchInitDataApi(initParams)
        .then(res => {
          if(res.status === 0) {
            // 从产品详情跳转过来时给产品数据赋值customerId
            if (pathName.indexOf('/event/createFromProduct') >= 0) {
              const event = res.data?.event || {}
              if (event.products?.length && event.cusId) {
                event.products.map(product => {
                  product.customerId = event.cusId
                  return product
                })
              }
            }
            this.initData = res.data
            // 复制事件过来的时候，query里面是没有 defaultTypeId 的 所以兼容一下
            if(!query.defaultTypeId && !query.newTemplateId) {
              // 从快捷方式进入事件
              const eventType = this.initData.eventTypeList && this.initData.eventTypeList[0]
              this.defaultTypeId = eventType?.id 
              initParams.defaultTypeId = eventType?.id
            }
          }
        })
    },

    initialize() {
      if (this.fromCopy && !this.typeListJson) {
        this.typeListJson = this.copyTypeListJson;
      }

      let workEvent = _.cloneDeep(this.event);
      if(this.callRecordId) {
        if(this.linkman) {
          // 客户
          workEvent.customer = this.linkman.customer
          workEvent.cusName = this.linkman.customer?.name
          workEvent.cusId = this.linkman.customerId
          // 联系人
          workEvent.lmName = this.linkman.name
          workEvent.lmPhone = this.linkman.phone
        }
        if(this.address){
          workEvent.validAddress = true
          workEvent.taddress = this.address
        }
      }
      this.workEvent = workEvent
      
      if(this.workEvent.id != null && !this.fromCopy){
        this.saveFormUrl = '/event/update';
      } else {
        this.saveFormUrl = this.callRecordId ? '/event/create4CallCenter' : '/event/createInner';
      }
      
      if (!this.workEvent.id || this.fromCopy) {
        // 检查版本数量限制
        this.checkNumExceedLimitBeforeHandler && this.checkNumExceedLimitBeforeHandler(
          TenantDataLimitSourceEnum.Event,
          TenantDataLimitTypeEnum.Event
        )
      }
    },

    // 获取事件类型字段
    async getEventTemplateFields() {
      const params = {
        tableName: 'event',
        templateId: this.isEdit ? this.workEvent.templateId : this.defaultTypeId,
        isFromSetting: true

      }
      
      let data = await EventApi.getEventTemplateFields(params)
      if(!this.isEdit) {
        data[0].fromCus = this.fromCus
        data[0].fromPro = this.fromPro

        this.workEvent.fromPro = this.fromPro;
        this.workEvent.fromCopy = this.fromCopy;
        this.workEvent.isAuto = this.isAuto

        if(this.workEvent.cusId){
          data[0].cusId = this.workEvent.cusId
          data[1].creatCus = 'false'
        }
        if(this.fromPro == 'true'){
          if(this.workEvent.products[0].id){
            data[0].proId = this.workEvent.products[0].id
            data[0].proName = this.workEvent.products[0].name
          }
        }
      }
      this.workEvent.myID = this.myID
      this.workEvent.myplayName = this.myplayName
      data[0].templateId = this.templateId
      data[0].templateName = this.templateName

      this.basicFields = data
      // 处理表单时间数据
      this.workEvent = disposeFormViewTime(this.basicFields, this.workEvent)
      // 处理富文本
      this.workEvent = await FormUtil.initRichTextContent(this.basicFields, this.workEvent);

      let form = util.packToForm(this.basicFields, this.workEvent);
      this.basicValue = FormUtil.initialize(this.basicFields, form);
      // 修复 编辑时联系人和地址 会强制更新为默认联系人和地址的问题
      this.$set(this.basicValue, 'isEdit', this.isEdit)
    },

    // 根据客户负责人更新事件分配协同人 但是得首先判断exeInSynOfTaskOrEvent属性
    updateSynergyByCustomer(customerId) {
      getCustomerExeinsyn({ id: customerId}).then(result => {
        if(result.succ && result.data?.userId) this.setSynergy([result.data])
      })
    },

    // 更新选中的事件类型
    updateEventTemplateId(template = {}) {
      this.taskTemplate = template || {};
    },

    eventAssignRadioChange(isAuto) {
      if(isAuto) {
        this.executorId = 'auto'
        this.executorName = ''
      } else {
        this.executorId = ''
        this.executorName = ''
      }
      this.$set(this.eventAssignForm, 'executorName', this.executorName)
    },

    // 返回
    handleBack() {
      
      try {
        
        const isInFrame = this.validateCurrentWindowIsInFrame()
        
        if (isInFrame) {
          this.postCloseDialogMessage()
          return
        }
        
      } catch (error) {
        console.error(error)
      }
      
      // parent.frameHistoryBack(window)
      let fromid = window.frameElement.getAttribute('fromid');
      if (!fromid || !this.isEdit) {
        const id = window.frameElement.dataset.id
        return this.$platform.closeTab(id)
      }
      let nowId = window.frameElement.getAttribute('id');
      backToFromAccurateTab(nowId)
    },

    // 保存
    handleSave: _.debounce(async function (p) {
      let basicEvent = {}
      let assignEvent = {}
      let isBasicValidate = false
      let isAssignValidate = false
      let isScrollToEventAssignFormFlag = false;
      // 事件基本信息
      await this.$refs.formEditRef.$refs.form.validate(false)
        .then(valid => {
          scrollIntoFirstRequireDom(this.$refs.formEditRef.$refs.form)
          if (!valid) return false;
          isScrollToEventAssignFormFlag = true;
          isBasicValidate = true
          // 处理国际化时间转换
          let formValue = disposeFormSubmitTime(this.basicFields, this.basicValue)
          basicEvent = util.packToEvent(this.basicFields, formValue);
          basicEvent = this.globalFormSubmissionDataProcessingHandler(this.basicFields, basicEvent)
          
          basicEvent.templateId = this.taskTemplate.value;
          basicEvent.templateName = this.taskTemplate.text;

        })
        .catch(err => {console.error(err)})

      if(this.showEventAllotInformation) {
        // 事件分配信息
        this.$refs?.eventAssignForm?.validate(valid => {
          if(isScrollToEventAssignFormFlag) this.$refs.eventAssignForm?.$el?.scrollIntoView({behavior: 'smooth'});
          if (!valid) return false
          isAssignValidate = true

          assignEvent = {
            executorId: this.executorId,
            executorName: this.executorName,
            synergies: this.synergies
          }
        });
      } else {
        isAssignValidate = true
      }

      if(!isBasicValidate || !isAssignValidate) return
      let params = Object.assign(this.workEvent, basicEvent, assignEvent)

      if(this.callRecordId) {
        params.callRecordId = this.callRecordId
      } 
      const query = parse(window.location.search) || {}
      if(query.conversationNo) {
        params.conversationNo = query.conversationNo
      }
      // 创建之前绑定客户和产品
      let isUnbind = params.products.filter(item=>!item.customerId).length // 判断是否有未关联的，需要提示
      if(this.productCreateUnBindCustomer && isUnbind){
        let nameArr = [], productIds = []
        params.products.filter(item=>!item.customerId).forEach(item=>{
          nameArr.push(item.name)
        })
        const confirmRes = await this.$confirm(this.$t('event.edit.text10', {data1: nameArr.join(',')}), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.makeSure'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning',
        })
        if(confirmRes){
          params.products.forEach(item=>{
            productIds.push(item.id)
          })
          let bindParams = {
            productIds,
            customerId:params.cusId,
            linkman:{
              id:params.lmId ? params.lmId : null
            },
            address:{
              id:params.cusAddress?.id ? params.cusAddress.id : null
            }
          }
          let bindRes = await bindCustomer(bindParams);
          if(!bindRes.success) return false
          // 客户绑定成功产品里面插入客户id
          params.products.forEach(item=>{
            item.customerId = params.cusId
          })
        }else{
          return false
        }
      }
      // 日程事件计划开始和完成时间
      if(p && p.planStartTime && p.planEndTime) {
        params.planStartTime = p.planStartTime
        params.planEndTime = p.planEndTime
      }
      if(params.planStartTime) params.planStartTime = safeNewDate(params.planStartTime).getTime() 
      if(params.planEndTime) params.planEndTime = safeNewDate(params.planEndTime).getTime()
      if(params.planStartTime && params.planEndTime && params.planStartTime > params.planEndTime) return this.$platform.notification({
        title: this.$t('common.modal.PLAN_END_TIME_NOT_LESS_THEN_PLAN_START_TIME_MEESSAGE'),
        type: 'error'
      });

      // 如果是自动分配校验事件自动分配规则是否可以匹配到负责人
      if(this.executorId == 'auto') {
        let checkAutoDispatchRes = await EventApi.checkAutoDispatch({event:params});
        if(checkAutoDispatchRes.status !== 0 ) return this.$message.warning(checkAutoDispatchRes.message)
      }    
          
      if(!this.isEdit) {
        const payload = !this.agendaEvent && this.isAuto ? this.eventAssignIsAuto ? this.$t('common.event.actionStatus.autoDispatch') : this.$t('event.edit.text2') : '';
        this.$track.clickStat(this.$track.formatParams('SAVE', payload));
      }
      
      if(this.isCopy) {
        params.state = null
        params.allotTime = null
        params.completeTime = null
        params.finishUsedTime = null
        params.finishUsedTimeStr = null
        params.startTime = null
      }
      
      try {
        this.setConnectorParamsForSubmit(params)
      } catch (error) {
        console.error(error)
      }
      
      this.loading = true

      if(this.isEdit && this.needServerDeleFiles.length){
        params.deleteFiles = this.needServerDeleFiles
      }

      this.$http.post(this.saveFormUrl, params)
        .then(res => {
          if (res.status == 0) { // 成功 刷新页面
            
            this.removeConnectorCreateSessionData()
           
            if(this.agendaEvent || this.urlParams.agendaEvent) {
              // 日程新建事件
              this.$platform.notification({
                title: res.message,
                type: 'success',
              })
              if (this.workEvent.id) { 
                // 日程编辑事件的时候关闭当前tab刷新日历tab 
                let closeId = window.frameElement.dataset.id
                this.$platform.closeTab(closeId)
                this.reloadTab()
              }else {
                this.$eventBus.$emit('agendar-create-event')
              }
            } else {
              // fix:22196,修复新建事件没有刷新列表
              let fromId = window.frameElement.getAttribute('fromid')
              let id = window.frameElement.getAttribute('id')
              if (fromId != id)  this.reloadTab()
              // window.location.href = this.joinParams(res.data)

              this.$platform.notification({
                title: this.$t('event.edit.text11', {data1: this.workEvent.id ? this.$t('common.base.update') : this.$t('common.base.create3')}),
                type: 'success',
              })
              
              if(res.data != null){
                let url = (res.data).indexOf('/event/view') >= 0 ? res.data : `/event/view/${res.data}`
                let eventId = url.split('/')[3] || ''
                this.closeAndOpenTab(eventId)
              }
            } 
            return
          }
          
          if (res.status == 2) { // 体验版数量限制
            // 打开版本数量限制弹窗 openVersionLimitDialog
            const initVersionLimitDialogFunction = initVersionLimitDialog
            if (!initVersionLimitDialogFunction && !isFunction(initVersionLimitDialogFunction)) return
            initVersionLimitDialogFunction()
            return
          }
          
          // TODO 需要审批判断改成errorCode
          if (Number(res.errorCode) == 10003){ // 审批
            this.workEventId = res.data.eventId;
            this.eventNo = res.data.eventNo || ''
            this.$refs.eventNeedApproveDialog.openDialog(res.data)

            // this.dialogForm.params = JSON.stringify(res.data)
            // this.dialogVisible = true
            return
          }else if (Number(res.errorCode) == 10004 && res.data?.needVipApprove){ // 高级审批
            this.workEventId = res?.data?.params?.eventId ?? '';
            this.eventNo = res.data?.params?.eventNo || ''
            this.$refs.AdvancedApprovalDialogRef?.openDialog(res.data)
            return
          }
          
          if (this.workEvent.id != null) { // 编辑时不会有审批
            this.$notify({
              title: this.$t('common.base.toast'),
              message: res.message,
              type: 'warning'
            });
            return
          }

          this.$platform.notification({
            title: res.message,
            type: 'error',
          })
          
          if (res.data != null){
            
            try {
                
              const isInFrame = this.validateCurrentWindowIsInFrame()
              
              if (isInFrame) {
                this.postCloseDialogMessage()
                return
              }
              
            } catch (error) {
              console.error(error)
            }
            
            this.removeConnectorCreateSessionData()

            // let { eventId = '' } = this.initParams
            let url = (res.data).indexOf('/event/view') >= 0 ? res.data : `/event/view/${res.data}`
            let eventId = url.split('/')[3] || ''
            this.closeAndOpenTab(eventId)
            // window.location.href = (res.data).indexOf('/event/view') >= 0 ? res.data : `/event/view/${res.data}`
          }

        })
        .catch(err => {console.error(err)})
        .finally(() => {this.loading = false})
    }, 1000),

    closeAndOpenTab(eventId) {
      
      try {
        
        const isInFrame = this.validateCurrentWindowIsInFrame()
        
        if (isInFrame) {
          this.postCloseDialogMessage()
          return
        }
        
      } catch (error) {
        console.error(error)
      }
      
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);
    
      let fromId = window.frameElement.getAttribute('id');
    
      openAccurateTab({
        type:PageRoutesTypeEnum.PageEventView,
        key:eventId,
        closeNowPage:true,
        fromId
      })
    },
    /**
     * @description 选择负责人和协同人
     */
    checkDept(type = 0) {
      // type 1协同人 0 负责人
      const name = !type ? 'team' : 'dept';
      let option = {
        title: type ? this.$t('event.edit.text8') : this.$t('event.edit.text9'), // [选填] 默认值为 '请选择人员'
        ...(type ? {max:100} : {max:1}),
        ...chooseExUser,
        mode: BaseSelectUserModeEnum.Filter
      };
      option.seeAllOrg = true
      if(this.agendaEvent) {
        option.unique = false
      }
      // 设置可以删除已经选择的人,组件内部传入selected
      option.selectedUsers = type == 0 ? this.executor : this.synergies
      // 过滤没有角色的用户
      option.haveRole = true
      if(this.showEventAllotInformation) {
        option.authKey = 'CASE_ALLOT';
      }
      this.$fast.select.multi.all(option).then(({ data, status }) => {
        if (!status) {
          if (type) {
            if(this.agendaEvent) {
              data.users = [...data.users]
            } 
            this.synergies = data.users;
            this.synergiesNames = data.users
              .map((item) => {
                return item.displayName;
              })
              .join(',');
            this.$eventBus.$emit('agendar-event-select-synergies', this.synergies);
          } else {
            const { userId, displayName } = data.users[0];
            this.executor = data.users[0];
            this.executorId = userId;
            this.executorName = displayName;
            this.$set(this.eventAssignForm, 'executorName', displayName)
            this.$eventBus.$emit('agendar-event-select-executor', this.executor);
          }
        }
      });
    },

    // 负责人选择我自己
    executorMySelf(event) {
      event.stopPropagation()
      this.executor = this.initData.currentUser;
      this.executorId = this.myID;
      this.executorName = this.myplayName;
      this.$set(this.eventAssignForm, 'executorName', this.myplayName)
      this.$eventBus.$emit('agendar-event-select-executor', this.executor);
    },
    
    // 关掉审批弹窗 （新建完成不审批）
    createEventWithoutApprove() {
      // const params = JSON.parse(this.dialogForm.params)
      //  window.location.href = `/event/view/${params.eventId}`;
      
      try {
        
        const isInFrame = this.validateCurrentWindowIsInFrame()
        
        if (isInFrame) {
          this.postCloseDialogMessage()
          return
        }
        
      } catch (error) {
        console.error(error)
      }
      
      let id = window.frameElement.dataset?.id;
      this.$platform.closeTab(id);
      
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        fromId,
        type:PageRoutesTypeEnum.PageEventView,
        key:this.workEventId
      });
      
    },
    reloadTab() {
      // 35171 【生产环境】【0304】复制“工单/事件”后对应的工单&事件列表不会自动刷新数据。
      // 复制事件时 fromId是当前详情页 所以没办法刷新列表 所以复制时 写死刷新事件列表
      if(this.isCopy) {
        this.$platform.refreshTab('frame_tab_M_SERVICE_EVENT')
      } else {
        let fromId = window.frameElement.getAttribute('fromid')
        this.$platform.refreshTab(fromId)
      }
    },
    getDeleteFiles(files){
      this.needServerDeleFiles = [...this.needServerDeleFiles,...files]
    }
  },
  components: {
    [EventEditForm.name]: EventEditForm,
    [EventNeedApproveDialog.name]: EventNeedApproveDialog,
    FormCellChange,
    AdvancedApprovalDialog,
  }
}
</script>
<style lang="scss">
body {
  padding: 12px;
}
</style>
<style lang="scss" scoped>
.event-detail-edit-view {
  height: 100%;
  overflow: hidden;
  border-radius: 4px;
  .operate-btn {
    padding: 16px;
    background: #fff;
    border-radius: 4px 4px 0 0;
    border-bottom: 1px solid #f4f7f5;
  }
  .event-form-container {
    width: 100%;
    height: calc(100% - 56px);
    overflow: auto;
  }
  .event-basic-info, .event-assign-info {
    background: #fff;
    overflow: hidden;
    .el-form {
      padding: 16px;
    }
    .info-title {
      padding: 16px;
      font-weight: bold;
      border-bottom: 1px solid #f4f4f4;
    }
    .info-content {
      padding: 12px;
      max-width: 824px;
      margin: 0 auto;
    }
    .info-content-forCell{
      max-width: 100%;
    }
  }
  .event-basic-info {
    border-radius: 0 0 4px 4px;
  }

  .event-assign-info {
    border-radius: 4px;
  }
  ::v-deep .el-form-item--small.el-form-item {
    .el-radio {
      margin-right: 10px;
    }
  }
  .p-input {
    display: flex;
    flex-wrap: wrap;
    border: 1px solid #e0e1e2;
    border-radius: 4px;
    padding: 0 10px;
    min-height: 32px;
    line-height: 30px;
    margin-bottom: 0;
    button {
      position: absolute;
      right: 0;
      height: 30px;
    }
  }
}
::v-deep .is-required:before {
  content: '';
}
.dialog-form {
  padding: 20px;
  ::v-deep .el-form-item--small.el-form-item{
    position: relative;
    .form-item-required {
      position: absolute;
      left: -36px;
      top: 3px;
    }
  }
}
</style>
<style lang="scss">
.agenda-event-edit-view {
  padding: 0;
}
.agenda-event-form {
  .form-builder{
    width: 100%; 
  }
}
.agenda-event-info-content{
  width: 100%!important;
}

.in-frame-modal-view {
  
  height: calc(100% - 60px);
  padding-bottom: 0;
  
  .base-form {
    position: relative;
    height: 100%;
  }
  
  .operate-btn {
    position: fixed;
    right: 20px;
    bottom: 10px;
    width: calc(100% - 32px);
    display: flex;
    justify-content: flex-end;
    padding-right: 40px;
  }
  
  .event-basic-info {
    padding-top: 16px;
  }
  
  .event-basic-info {
    overflow-y: scroll;
    width: 100%;
    padding: 0 20px;
    margin-top: 0;
  }
  
}
</style>.